package com.jianye.recycdona.control.http;

import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jianye.recycdona.control.Apps;
import com.jianye.recycdona.control.bean.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.jianye.recycdona.control.Apps.JSON;

public class UserOkHttp {

    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    //2.定义全局唯一的一个对象，做私有化处理不让外界之间调用；
    private static UserOkHttp myOkHttp=new UserOkHttp();

 //标识未存-----1标识已经存入后台
    private String ResponseMsg;

    //标识码
    public String codeStatus="0";

    private final Gson gson=common.getGson();

    private    static final OkHttpClient  client= common.getClient();


    //手机号  0标识未存-----1标识已经存入后台,
    public String getResponseMsg() {
        return ResponseMsg;
    }

    //1.构造方法私有化，防止外部调用构造方法创建对象
    private UserOkHttp() {
    }
    //3.提供公共的全局方法供外界获取，返回对象实例，
    public static UserOkHttp getMyOkHttp(){
        return myOkHttp;
    }


    /**
     * 发送验证码
     * @return
     */
    public int sendcode(String smsUrl) {

//        try {
//            listsms= CommentHttp.getMyOkHttp().getsmsapi();
//        } catch (ExecutionException | InterruptedException e) {
//            e.printStackTrace();
//        }
//        String acoun= listsms.get(0).getAcount();
//        String url=listsms.get(0).getUrl();
//        String secretkey=listsms.get(0).getSecretkey();
//        String template=listsms.get(0).getTemplate();
//        String URL =url+"?"+"appid="+acoun+"&appsecret="+secretkey+"&code="+code+"&mobile="+mobile+"&template_id="+template;
//       // https://yiketianqi.com/api/sms?appid=45121489&appsecret=96nzoUY
//        Log.d(TAG, "------------------------------------->URL: "+APISMS);

        Request request=new Request.Builder().url(smsUrl).get().build();
        try {
            Response response=client.newCall(request).execute();
            String msg=response.body().string();
            Log.w("Phonecode","--------------->"+msg);
            MsgInfo mssgs=gson.fromJson(msg, MsgInfo.class);
            if (mssgs.getCode()==0){
                return 0;
            }else {
                return 1;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return 1;
        }
    }



    /**
     * 为HttpGet 的 url 方便的添加多个name value 参数。
     * @param url
     * @param params
     * @return
     */
    public static String attachHttpGetParams(String url, LinkedHashMap<String,String> params){

        Iterator<String> keys = params.keySet().iterator();
        Iterator<String> values = params.values().iterator();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("?");

        for (int i=0;i<params.size();i++ ) {
            String value=null;
            try {
                value= URLEncoder.encode(values.next(),"utf-8");
            }catch (Exception e){
                e.printStackTrace();
            }

            stringBuffer.append(keys.next()+"="+value);
            if (i!=params.size()-1) {
                stringBuffer.append("&");
            }
            Log.v("stringBuffer-userphone","----------->"+stringBuffer.toString()+"");
        }

        return url + stringBuffer.toString();
    }

    /**
     * http://106.15.74.249/api/recyclerUser/findbyphone
     * @param phone
     * 检查手机号是否注册
     * @return
     */
    public void chekPhone(String phone) throws ExecutionException, InterruptedException {

        CheckPhoneReginster callableThread = new CheckPhoneReginster(phone);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
    }

    class CheckPhoneReginster implements Callable {


        private String phone;

        public CheckPhoneReginster(String phone) {
            this.phone = phone;
        }

        @Override
        public Object call() throws Exception {
            LinkedHashMap<String,String> linkedHashMap=new LinkedHashMap<>();
            linkedHashMap.put("phone",phone);
            String url=attachHttpGetParams(Apps.findbyphone,linkedHashMap);
            try {
                Request request = new Request.Builder()
                        .url(url)//请求接口。如果需要传参拼接到接口后面。
                        .build();//创建Request 对象
                Response response = null;
                response = client.newCall(request).execute();//得到Response 对象
                if (response.isSuccessful()) {
                    assert response.body() != null;
                    ResponseMsg=response.body().string();//返回值为1则已经注册0为未注册
                    Log.d("ResponseMsg", "------------->"+response.code()+ResponseMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            Thread.currentThread();
            return "Hollis";
        }

    }

    /**
     * 登录
     * @param ：手机号
     * url : http:/106.15.74.249/api/recyclerUser/adduser
     *  ResponseMsg=0/1   0标识未存-----1标识已经存入后台
     * @return
     */
    public String Login(String phone) throws ExecutionException, InterruptedException {
        LoginThread callableThread = new LoginThread(phone);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
        return codeStatus;
    }

    class LoginThread implements Callable {
        private String phone;

        public LoginThread(String phone) {
            this.phone = phone;
        }

        @Override
        public Object call() throws Exception {
            System.out.println(Thread.currentThread().getName());

            if (ResponseMsg.equals("0")){
                try {
                    //传的json
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("phone",phone);
                    String callStr = UserOkHttp.post(Apps.adduser, jsonObject.toString());
                    JSONObject call_json = new JSONObject(callStr);
                    codeStatus = call_json.getString("status");
                    Log.e("Logincode", "------------------------------->"+codeStatus);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
            return "ok";
        }

    }



    public static String post(String url, String json) throws IOException {

        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }


    /***
     *查询用户信息
     */
    public int getUserinfo(String phone, SharedPreferences sp) throws ExecutionException, InterruptedException {
        SelectUserinfo callableThread = new SelectUserinfo(phone,sp);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
        return 200;
    }

    class SelectUserinfo implements Callable {
        private String phone;
        SharedPreferences sp;

        public SelectUserinfo(String phone, SharedPreferences sp) {
            this.phone = phone;
            this.sp = sp;
        }
        @Override
        public Object call() throws Exception {

            //url拼接
            LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
            linkedHashMap.put("phone", phone);

            String url = attachHttpGetParams(Apps.selectuserinfo, linkedHashMap);
            Log.e("url", "-------------------------------------->" + url);

            Request request = new Request.Builder()
                    .url(url)//请求接口。如果需要传参拼接到接口后面。
                    .build();//创建Request 对象
            Response response = null;
            response = client.newCall(request).execute();//得到Response 对象


            if (response.isSuccessful()) {

                try {
                    assert response.body() != null;
                    String msginfo = response.body().string();

                    Log.e("msg", "------------------------------------" + msginfo);
                    User fromJson = gson.fromJson(msginfo, User.class);

                    //存储到本地数据
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("id", fromJson.getData().getId()+"");//用户唯一标识id
                    editor.putString("username", fromJson.getData().getUsername());
                    editor.putInt("point", fromJson.getData().getPoint());

                    if (fromJson.getData().getSex() == null) {
                        editor.putString("sex", "");
                    } else {
                        editor.putString("sex",fromJson.getData().getSex());
                    }

                    editor.putString("phone", fromJson.getData().getPhone());
                    editor.apply();

                    Log.e("userinfo", "------------------------------>" + fromJson.getStatus() + fromJson.getMsg());

                } catch (IOException | JsonSyntaxException e) {
                    e.printStackTrace();
                }


            }

            return "Clable ok";
        }
    }




    /**
     * 修改用户信息
     * id 用户id
     * Filed 要修改的字段
     * info  修改的数据
     */

    public void Updateinfo(String id,String filde,String info) throws ExecutionException, InterruptedException {
        UpdateUserInfo callableThread = new UpdateUserInfo(id,filde,info);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
    }

    class UpdateUserInfo implements Callable {
        private String id;
        private String Field;
        private String info;

        public UpdateUserInfo(String id, String field, String info) {
            this.id = id;
            Field = field;
            this.info = info;
        }

        @Override
        public Object call() throws Exception {

            //传的json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", id+"");
            jsonObject.put(Field, info);

            String callStr = put(jsonObject.toString());
            JSONObject call_json = new JSONObject(callStr);
            final String code = call_json.getString("status");
            Log.e("UpdateInfocode", code + "-------------------------------code");

            System.out.println(Thread.currentThread().getName());
            return "OK";
        }

    }

    public   String put(String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(Apps.updateUserInfo)
                .put(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            assert response.body() != null;
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }

    }

    class MsgInfo {
        /**
         * errcode : 0
         * errmsg : SUCCESS
         */
        private int code;
        private String msg;
        private String contentinfo;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public String getContentinfo() {
            return contentinfo;
        }

        public void setContentinfo(String contentinfo) {
            this.contentinfo = contentinfo;
        }
    }
}
